<?php
class ContactsAction extends Action {
	private $uid = '';
	/*======================================================================*\
		Function:	_initialize
		Purpose:	初始化一些参数，主要判断是否登录授权
		Input:		无	            空
		Output:		无      		空
	\*======================================================================*/
	public function _initialize(){
		
		$this->_uid = session('uid');
		if(!$this->_uid) $this->display("Public:login");//(503,"对不起，您登录超时了，请重新登录！",1);
		//B('Authenticate', $action);
	}
	/*======================================================================*\
		Function:	categoryAdd
		Purpose:	客户分类管理-添加分类
		Input:		无	            空
		Output:		模板输出      	#
	\*======================================================================*/
	public function categoryAdd(){
		$Category = M('Category');
		$get = $this->_get();
		$uid = $this->_uid;
		if($get['category_name']){
			$data = array(
				'owner_uid'	=> $uid,
				'category_name' => $get['category_name']
			);
			$v = $Category->where($data)->find();
			if($v){
				$this->ajaxReturn(0,'分类名已经存在',0);
			}else{
				$v = $Category->add($data);
				if($v){
					$this->ajaxReturn(1,'添加成功',1);
				}else{
					$this->ajaxReturn(0,'添加失败',0);
				}
			}
		}else{
			$this->ajaxReturn(0,'分类名不能为空',0);
		}
	}
	/*======================================================================*\
		Function:	categoryEdit
		Purpose:	客户分类管理- 修改分类
		Input:		无	            空
		Output:		模板输出      	#
	\*======================================================================*/
	public function categoryEdit(){
		$Category = M('Category');
		$get = $this->_get();
		$uid = $this->_uid;
		if($get['category_name'] && $get['category_id']){
			$data = array(
				'category_id'	=> $get['category_id'],
				'category_name' => $get['category_name']
			);
			$v = $Category->where("uid = '$uid'")->save($data);
			if($v){
				logs($uid,"分类名修改成功",1)
				$this->ajaxReturn(1,'分类名修改成功',1);
			}else{
				logs($uid,"分类名修改失败",0)
				$this->ajaxReturn(0,'分类名修改失败',0);
				
			}
		}else{
			$this->ajaxReturn(0,'分类名不能为空',0);
		}

	}
	/*======================================================================*\
		Function:	categoryDel
		Purpose:	客户分类管理- 删除分类
		Input:		无	            空
		Output:		模板输出      	#
	\*======================================================================*/
	public function categoryDel(){
		$Category = M('Category');
		$get = $this->_get();
		$uid = $this->_uid;
		if($get['category_id']){
			$data = array(
				'category_id'	=> $get['category_id'],
				'owner_uid' => $uid
			);
			$v = $Category->where($data)->delete();
			if($v){
				logs($uid,"分类删除成功",1)
				$this->ajaxReturn(1,"分类删除成功",1);
			}else{
				logs($uid,"分类删除失败",0)
				$this->ajaxReturn(0,"分类删除失败",0);
				
			}
		}else{
			$this->ajaxReturn(0,'获取分类ID失败',0);
		}
	}
	/*======================================================================*\
		Function:	getCategory
		Purpose:	客户分类管理- 获取分类
		Input:		无	            空
		Output:		模板输出      	#
	\*======================================================================*/
	
	public function getCategory(){
		$Category = M('Category');
		$uid = $this->_uid;
		if($uid){
			$data = array(
				'owner_uid' => $uid
			);
			$v = $Category->where($data)->select();
			if($v){
				$this->ajaxReturn($v,"分类获取成功",1);
			}else{				
				$this->ajaxReturn(0,"分类为空",0);
			}
		}else{
			$this->ajaxReturn(0,'你确定你登录了吗？',0);
		}

	}












	public function test(){
			$input = "10101010101010101010";
			$input = str_split($input);
			dump($input);
	}
	/*======================================================================*\
		Function:	excelExport
		Purpose:	以excel方式批量导出联系人
		Input:		params	        参数
		Output:		文档输出      	#
	\*======================================================================*/
	public function excelExport(){
		import("ORG.PHPExcel.PHPExcel");
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("十目科技");
		$objProps->setLastModifiedBy("十目科技");    
		$objProps->setTitle("十目科技通讯录");    
		$objProps->setSubject("十目科技通讯录");    
		$objProps->setDescription("十目科技通讯录");    
		$objProps->setKeywords("十目科技通讯录");    
		$objProps->setCategory("十目科技通讯录");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
	    $matchCn = array('姓名','手机','身份证号','生日','性别','公司名称','公司电话','公司传真','公司部门','公司职务','公司邮箱','公司网址','公司邮编','公司地址','昵称','私人QQ','私人邮箱','私人邮编','私人网址','家庭地址');
		$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');  
		$input = "11111111111111111111";
		$icount = strlen($input);
		
		
		
		$mcount = count($matchCn);
		$input = str_split($input);
		if($icount != $mcount){
			$error['msg'] = "参数出错";
			
		}else{
			$objActSheet->setTitle('Sheet1');
			$A = 'A';
			$k = 0;
			foreach($input as $idata){
				if($idata){
					$objActSheet->setCellValue($A.'1', $matchCn[$k]);
					$MC[] = $matchEn[$k];
					$A++;
				}
				$k++;
			}
			/**
			$objActSheet->setCellValue('A1', '姓名');
			$objActSheet->setCellValue('B1', '尊称');
			$objActSheet->setCellValue('C1', '部门');
			$objActSheet->setCellValue('D1', '职位');
			$objActSheet->setCellValue('E1', '电话');
			$objActSheet->setCellValue('F1', 'Email');
			$objActSheet->setCellValue('G1', '地址');
			$objActSheet->setCellValue('H1', '邮编');
			$objActSheet->setCellValue('I1', '备注');
			$objActSheet->setCellValue('J1', '所属客户');
			$objActSheet->setCellValue('K1', '负责人');
			$objActSheet->setCellValue('L1', '创建人');
			$objActSheet->setCellValue('M1', '创建时间');
			**/

			//$where['owner_role_id'] = array('in',implode(',', getSubRoleId()));
			$list = M('contacts')->where($where)->select();
			$i = 1;
			foreach ($list as $k => $v) {
				$i++;
				$owner = D('RoleView')->where('role.role_id = %d', $v['owner_role_id'])->find();
				$creator = D('RoleView')->where('role.role_id = %d', $v['creator_role_id'])->find();
				//整理数据输出
				$imc = 0;
				for($ik = 'A';$ik <= $A;$ik++){
					$name = $MC[$imc];
					$objActSheet->setCellValue($ik.$i, $v[$name]);
					$imc++;
				}
				/*
				$objActSheet->setCellValue('A'.$i, $v['name']);
				$objActSheet->setCellValue('B'.$i, $v['mobile']);
				$objActSheet->setCellValue('C'.$i, $v['email']);
				$objActSheet->setCellValue('D'.$i, $v['address']);
				$objActSheet->setCellValue('E'.$i, $v['company']);
				$objActSheet->setCellValue('F'.$i, $v['department']);
				$objActSheet->setCellValue('G'.$i, $v['description']);
				*/
				
			}
			/*输出一些其他信息
			$customer_id = M('rContactsCustomer')->where('contacts_id = %d', $v['contacts_id'])->getField('customer_id');
				$customer_name = M('customer')->where('customer_id = %d' ,$customer_id)->getField('name');
				$objActSheet->setCellValue('J'.$i, $customer_name);
				$objActSheet->setCellValue('K'.$i, $owner['user_name'] .'['.$owner['department_name'].'-'.$owner['role_name'].']');
				$objActSheet->setCellValue('L'.$i, $creator['user_name'].'['.$creator['department_name'].'-'.$creator['role_name'].']');
				$objActSheet->setCellValue('M'.$i, date("Y-m-d H:i:s", $v['create_time']));
			*/
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			header("Content-Type: application/vnd.ms-excel;");
			header("Content-Disposition:attachment;filename=sm_contacts_".date('Y-m-d',mktime()).".xls");
			header("Pragma:no-cache");
			header("Expires:0");
			$objWriter->save('php://output'); 
		
		}
		
	}
	/*======================================================================*\
		Function:	excelImport
		Purpose:	以excel方式批量导入联系人
		Input:		文档输入	        参数
		Output:		ajax		    	#
	\*======================================================================*/
	public function excelImport(){
		$m_contacts = M('Contacts');
		if (isset($_FILES['excel']['size']) && $_FILES['excel']['size'] != null) {
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 100000000 ;// 设置附件上传大小
			$upload->allowExts  = array('xls');// 设置附件上传类型
			$upload->savePath =  './Uploads/contacts/';// 设置附件上传目录
			$upload->saveRule = 'time';
			$upload->autoSub = true; //开启子目录保存
			$upload->subType = 'date';//子目录以日期格式保存
			$upload->dateFormat = 'Ym/d';//子目录日期模式下保存格式
			$upload->autoCheck = true;
			$dirname = './Uploads/contacts/';// . date('Ym', time()).'/'.date('d', time()).'/'
			if (!is_dir($dirname) && !mkdir($dirname, 0777, true)) {
				$error['msg'] = "附件上传目录不可写";
			}
			if(!$upload->upload()) {// 上传错误提示错误信息
			$this->error($upload->getErrorMsg());
			}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();   //$info[0]['savename'];
			}	
			$filename = $info[0]['savename'];
		}
		
		if(is_array($info[0]) && !empty($info[0])){
			$savePath = $dirname . $info[0]['savename'];
		}else{
			$error['msg'] .= "上传失败";
		}
		import("ORG.PHPExcel.PHPExcel");
		$PHPExcel = new PHPExcel();
		$PHPReader = new PHPExcel_Reader_Excel2007();
		if(!$PHPReader->canRead($savePath)){
			$PHPReader = new PHPExcel_Reader_Excel5();
		}
		$PHPExcel = $PHPReader->load($savePath);
		$currentSheet = $PHPExcel->getSheet(0);
		$currentSheet->getStyle()->getFont()->applyFromArray(
	 		array(
	 			'name'	  => 'Arial'
	 			)
	 	);
	    
		$allRow = $currentSheet->getHighestRow();
		
		$matchCn = array('姓名','手机','身份证号','生日','性别','公司名称','公司电话','公司传真','公司部门','公司职务','公司邮箱','公司网址','公司邮编','公司地址','昵称','私人QQ','私人邮箱','私人邮编','私人网址','家庭地址');
		$matchEn = array('name','mobile','identification_card','birthday','gender','company','comtel','comfax','comdepartment','job','comemail','comwebsite','comzip','comaddress','nickname','privateqq','privateemail','privatezip','privatewebsite','address');
	//--------------------------------------
	//整理要导入的具体项目
		$flag = 1;
		$AZ = 'A';
		$MT = array();
		$error['msg'] .= "以下格式不对:";
		while($flag){
			
			$value = $currentSheet->getCell($AZ.'1')->getValue();
			if($value == '') {
				$flag = 0;
				break;
			}
		
			echo $value;
			$k = 0;
			$is = false;
			foreach($matchCn as $m){
				if($value == $m){
					$iflag = $flag - 1;
					
					$MT[] = array(
						'position' => $AZ,
						'en'       => $matchEn[$k]
					);
					$is = true;
					echo $matchEn[$k];
					break;
				}
				$k++;
			}
			if(!$is){
				$error = $error.$value."--";
			}
			$AZ++;
			$flag++;	
		}
//--------------------------------------
		for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
			$data = array();
			$data['uid'] = session('uid');
			$data['create_time'] = date('Y-m-d H:i:s');
			$data['update_time'] = date('Y-m-d H:i:s');
			$data['owner_uid'] = trim($_POST['owner_role_id']);
//------------------------------------------
foreach($MT as $mt){
	$currentSheet->getStyle($mt['position'].$currentRow)->getFont()->applyFromArray(array('name' => 'Arial'));
	//dump($currentSheet->getStyle($mt['position'].$currentRow)->getFont());
	//echo $mt['position'].$currentRow;
	$objStyleAZ = $currentSheet->getStyle($mt['position'].$currentRow);  
  
	//设置单元格内容的数字格式。  
	//  
	//如果使用了 PHPExcel_Writer_Excel5 来生成内容的话，  
	//这里需要注意，在 PHPExcel_Style_NumberFormat 类的 const 变量定义的  
	//各种自定义格式化方式中，其它类型都可以正常使用，但当setFormatCode  
	//为 FORMAT_NUMBER 的时候，实际出来的效果被没有把格式设置为"0"。需要  
	//修改 PHPExcel_Writer_Excel5_Format 类源代码中的 getXf($style) 方法，  
	//在 if ($this->_BIFF_version == 0x0500) { （第363行附近）前面增加一  
	//行代码:   
	//if($ifmt === '0') $ifmt = 1;  
	//  
	//设置格式为PHPExcel_Style_NumberFormat::FORMAT_NUMBER，避免某些大数字  
	//被使用科学记数方式显示，配合下面的 setAutoSize 方法可以让每一行的内容  
	//都按原始内容全部显示出来。  
	$objStyleAZ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);    
	//设置字体  
	$objFontA5 = $objStyleAZ->getFont();  
	$objFontA5->setName('新宋体');  
	$cv = $currentSheet->getCell($mt['position'].$currentRow)->getValue();
	$var = $mt['en'];
	$cv != '' && $cv != null ? $data[$var]= $cv : ''; ; 
}
//------------------------------------------
/*			$name = $currentSheet->getCell('A'.$currentRow)->getValue();
			$name != '' && $name != null ? 
			$mobile = $currentSheet->getCell('B'.$currentRow)->getValue();
			$mobile != '' && $mobile != null ? $data['mobile'] = $mobile : '';
			$gender = $currentSheet->getCell('C'.$currentRow)->getValue();
			$gender != '' && $gender != null ? $data['gender'] = $gender : '';
			$email = $currentSheet->getCell('D'.$currentRow)->getValue();
			$email != '' && $email != null ? $data['email'] = $email : '';
			$address = $currentSheet->getCell('E'.$currentRow)->getValue();
			$address != '' && $address != null ? $data['address'] = $address : '';
			$company = $currentSheet->getCell('F'.$currentRow)->getValue();
			$company != '' && $company != null ? $data['company'] = $company : '';				
			$department = $currentSheet->getCell('G'.$currentRow)->getValue();
			$department != '' && $department != null ? $data['department'] = $department : '';
			$description = $currentSheet->getCell('H'.$currentRow)->getValue();
			$description != '' && $description != null ? $data['description'] = $description : '';
			dump($data);

		*/
			if(!$m_contacts->add($data)) {
				alert('error', '导入至第' . $currentRow . '行出错', U('leads/index'));
				$error['msg'] .= '导入至第' . $currentRow . '行出错';
				break;
			}
		
			
		} 
	}
}